import { NativePageTransitions, NativeTransitionOptions } from '@ionic-native/native-page-transitions';
import { Router } from '@angular/router';
import { Network } from '@ionic-native/network';
import { OnDestroy } from '@angular/core';
import { Platform } from 'ionic-angular';
import { CODE_PUSH_DEPLOYMENT_KEY } from '../providers/secretKey'
import { IsDebug } from '@ionic-native/is-debug';
import { CodePush } from '@ionic-native/code-push';


export class Tools implements OnDestroy{

  options: NativeTransitionOptions
  netStatus: Boolean = true
  private disconnectObs
  private connectObs
  public isDebug:IsDebug;
  public platform:Platform;
  public codepush: CodePush;

  constructor(
    protected route:Router,
    protected nativePageTransitions:NativePageTransitions,
    protected network: Network
  ){
    this.init()
    this.options = {
      duration: 500,
      iosdelay: 100,
      androiddelay: 150
     };
     // 订阅离线消息
    this.disconnectObs = this.network.onDisconnect().subscribe(() => {
      this.netStatus = false
    });
    // 订阅上线消息
    this.connectObs = this.network.onConnect().subscribe(() => {
      this.netStatus = true
    })
  }

  init(){ // 手动  实例化
    this.isDebug = new IsDebug();
    this.platform = new Platform();
    this.codepush = new CodePush();
  }

  openPage(path:String,params?:any){
    this.nativePageTransitions.fade(this.options);
    this.route.navigate([path])
  }
  goback(){
    this.nativePageTransitions.fade(this.options);
    this.route.navigate(['home'])
  }

  go(url:string){
    this.nativePageTransitions.fade(this.options);
    this.route.navigateByUrl(url)
  }

  getNetworkInfo():Boolean{
    return this.netStatus
  }
  delayRun(fn,time){
    setTimeout(fn,time)
  }

  getdebug(fn){
    this.isDebug.getIsDebug()
      .then((isDebug: boolean) => {
        fn(isDebug)
      })
      .catch((error: any) => {
        fn(false)
      });
  }

  getDeploymentKey(debug){
    //如果不是真机环境return
    if (!this.isMobile()) return '';
    //发布的key
    let deploymentKey = '';
    //如果是Android环境 并且是 debug模式
    if (this.isAndroid() && debug)
    {
      deploymentKey = CODE_PUSH_DEPLOYMENT_KEY.ANDROID.Staging;
    }
    if (this.isAndroid() && !debug)
    {
      deploymentKey = CODE_PUSH_DEPLOYMENT_KEY.ANDROID.Production;
    }
    if (this.isIos() && debug)
    {
      deploymentKey = CODE_PUSH_DEPLOYMENT_KEY.IOS.Staging;
    }
    if (this.isIos() && !debug)
    {
      deploymentKey = CODE_PUSH_DEPLOYMENT_KEY.IOS.Production;
    }
    return deploymentKey
  }

  checkUpdateApp(downsuccess,downerror,installsuccess,installerr,noupdate){
    this.getdebug((debug) => {
      var deployKey = this.getDeploymentKey(debug)
      this.codepush.checkForUpdate(deployKey).then((remotepackage) => {
        if (remotepackage) { // 存在更新包
          remotepackage.download((localpackage) => {
            localpackage.install(() => {
              installsuccess()
            },() => {
              installerr()
            })
          },(err) => {
            downerror(err)
          },(downprogress) => {
            downsuccess(downprogress)
            console.log('下载进度',downprogress);
            console.log('下载总量',downprogress.totalBytes);
            console.log('接收到的数据',downprogress.receivedBytes)
          })
        } else {
          // 当前已经是最新版本
          noupdate()
        }
      })
    })
  }

  onlyCheckUpdate(fn){
    this.getdebug((debug) => {
      var deployKey = this.getDeploymentKey(debug)
      this.codepush.checkForUpdate(deployKey).then((remotepackage) => {
        if (remotepackage) {
          fn()
        }
      })
    })
  }

  /**
   * 是否是真机环境
   * @returns {boolean}
   * @memberof NativeService
   */
  isMobile(): boolean
  {
    return this.platform.is("mobile") && !this.platform.is("mobileweb");
  }

  /**
   * 是否android真机环境
   * @returns {boolean}
   * @memberof NativeService
   */
  isAndroid(): boolean
  {
    return this.isMobile() && this.platform.is("android");
  }

  /**
   * 是否是ios真机环境
   * @returns {boolean}
   * @memberof NativeService
   */
  isIos(): boolean
  {
    return this.isMobile() && (this.platform.is("ios") || this.platform.is("ipad") || this.platform.is("iphone"));
  }

  ngOnDestroy(){
    this.disconnectObs.unsubscribe()
    this.connectObs.unsubscribe()
  }
}
